package com.xinyin.aiqinhaiback.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/firstView")
@Component
public class MyWebSocket {

	private static Logger logger = LoggerFactory.getLogger(MyWebSocket.class);
	private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
	private Session session;
	private static int connectCount = -1;
	// 记录当前连接数
 	public static CopyOnWriteArraySet<MyWebSocket> getWebSocketSet(){
 		return webSocketSet;
	}
	public MyWebSocket() throws InterruptedException {
	}
	@OnOpen
	public void onOpen(Session session) {
		this.session = session;
		webSocketSet.add(this);
		connectCount++;
		logger.info("新客户端链接进入");
	}
	@OnClose
	public void onClose() {
		webSocketSet.remove(this);
		connectCount--;
//        serialPort.removeEventListener();
//        serialPort.close();

	}
	@OnMessage
	public void onMessage(String message, Session session) {
		logger.info("收到来自客户端的消息: {}", message);
	}
	public static synchronized  void sendMessage(String message) {
		for (MyWebSocket webSocket : webSocketSet) {
			try {
				webSocket.session.getBasicRemote().sendText(message);
			} catch (IOException e) {
				logger.error("向客户端发送消息出错", e);
			}
		}
	}

	@OnError
	public void onError(Throwable throwable) {
		logger.error("WebSocket发生错误", throwable);
	}
}
